/*
 * rain.c
 *
 *  Created on: Sep 14, 2020
 *      Author: daniel
 */

#include "rain.h"
#include "stm32l0xx_hal.h"
#include <ws_data.h>

#include <stdbool.h>

static uint32_t		rain_total;			// 0.1mm为基础单位

void Rain_Init()
{
	// 从Backup寄存器读取Rain总量
	do {
		if (RTC->BKP0R == ~RTC->BKP1R) {
			rain_total = RTC->BKP0R;
			RTC->BKP2R = rain_total;
			RTC->BKP3R = ~rain_total;

			break;
		}

		if (RTC->BKP2R == ~RTC->BKP3R) {
			rain_total = RTC->BKP2R;
			RTC->BKP0R = rain_total;
			RTC->BKP1R = ~rain_total;

			break;
		}

		// 两个全错，复位为0
		rain_total = 0;

		RTC->BKP0R = rain_total;
		RTC->BKP1R = ~rain_total;
		RTC->BKP2R = rain_total;
		RTC->BKP3R = ~rain_total;
	} while (0);
}

static uint32_t tickLast = 0;

void rain_ISR()
{
	// 防抖处理
	uint32_t	tickNow = ws_GetCount();

	// 125ms * 10
	if ((tickNow - tickLast) < 10) {
		return;
	}

	tickLast = tickNow;

	rain_total += 5;				// +0.5mm

	// 保存到Backup寄存器上
	RTC->BKP0R = rain_total;
	RTC->BKP1R = ~rain_total;
	RTC->BKP2R = rain_total;
	RTC->BKP3R = ~rain_total;
}

uint32_t GetRainTotal()
{
	uint32_t	data;

	// 关闭中断，拷贝数据，避免读取错误
	__disable_irq();
	data = rain_total;
	__enable_irq();

	return data;
}
